package com.example.bbs.ui.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.bbs.R;
import com.example.bbs.base.Data;
import com.example.bbs.bean.Post;
import com.example.bbs.config.HttpConstant;
import com.example.bbs.util.BaseUtil;
import com.example.bbs.util.HttpUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import okhttp3.FormBody;

public class DraftBoxActivity extends AppCompatActivity {

    public class ItemViewHolder extends RecyclerView.ViewHolder {

        Post post;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            itemView.setOnClickListener((v) -> {
                Intent intent = new Intent(DraftBoxActivity.this, EditActivity.class);
                intent.putExtra(DisplayActivity.INTENT_EXTRA_POST, post);
                startActivity(intent);
            });
        }

        public void setPost(Post post) {
            this.post = post;

            TextView titleTextView = itemView.findViewById(R.id.tv_item_title);
            titleTextView.setText(post.getTitle());
            TextView contentTextView = itemView.findViewById(R.id.tv_item_content);
            contentTextView.setText(post.getAbstractContent());
        }
    }

    public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @NonNull
        @Override
        public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(parent.getContext(), R.layout.view_item_draft_box, null);
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ((ItemViewHolder)holder).setPost(mDraftList.get(position));
        }

        @Override
        public int getItemCount() {
            return mDraftList.size();
        }
    }

    static final String LOG_TAG = DraftBoxActivity.class.getSimpleName();
    static final int MIN_REFRESHING_TIME = 1000; // milliseconds

    SwipeRefreshLayout srlDraftList;
    RecyclerView rvDraftList;
    MyAdapter mAdapter = new MyAdapter();
    List<Post> mDraftList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(LOG_TAG, "onCreate");
        setContentView(R.layout.activity_draft_box);
        initView();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void initView() {
        srlDraftList = findViewById(R.id.srl_draft_list);
        srlDraftList.setColorSchemeColors(getResources().getColor(R.color.primary, null));
        rvDraftList = findViewById(R.id.rv_draft_list);
        rvDraftList.setAdapter(mAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvDraftList.setLayoutManager(layoutManager);

        srlDraftList.setOnRefreshListener(() -> {
            long startTime = System.currentTimeMillis();
            CompletableFuture.runAsync(() -> {
                load();
                long waitingTime = startTime + MIN_REFRESHING_TIME - System.currentTimeMillis();
                if (waitingTime > 0) {
                    srlDraftList.postDelayed(() -> {
                        if (srlDraftList != null && srlDraftList.isRefreshing()) {
                            srlDraftList.setRefreshing(false);
                        }
                        mAdapter.notifyDataSetChanged();
                    }, waitingTime); // 延时一段时间，关闭下拉刷新
                } else {
                    runOnUiThread(() -> {
                        if (srlDraftList != null && srlDraftList.isRefreshing()) {
                            srlDraftList.setRefreshing(false);
                        }
                        mAdapter.notifyDataSetChanged();
                    });
                }
            });
        });
    }
    
    private void load() {
        if (Data.myself == null) {
            BaseUtil.showToast(R.string.toast_please_login);
            return;
        }
        JSONObject json = HttpUtil.post(HttpConstant.REQUEST_QUERY_DRAFT, "");
        if (json == null || !json.getBoolean(HttpConstant.FIELD_REPLY))
            return;
        JSONArray result = json.getJSONArray(HttpConstant.FIELD_DATA);
        mDraftList.clear();
        for (int i = 0; i < result.size(); i++) {
            Post newDraft = result.getObject(i, Post.class);
            newDraft.setType(Post.TYPE_DRAFT);
            mDraftList.add(newDraft);
            Log.d(LOG_TAG, "draft box updated: num: " + mDraftList.size());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(LOG_TAG, "onResume");

        try {
            CompletableFuture.runAsync(this::load).get(); // 初始化
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(LOG_TAG, "onPause");
    }
}

